package com.laikan.reader.bookreader.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.BookDesRequester;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.CommentAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.CommentBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.BookFileUtils;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.ShareSdkReadBookShare;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SimpleTagImageView;
import com.laikan.reader.core.view.SnackBarNotice;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import static android.view.View.VISIBLE;

/**
 * 评论列表
 *
 * @author wxl
 */
public class CommentActivity extends BasicActivity {

    @SuppressWarnings ("rawtypes")
    private BaseDataBean<BaseListDataBean<CommentBean>> result;
    private ArrayList<CommentBean> mCommentDataList;
    private HashSet mCommentIdList = new HashSet();
    private CommentAdapter mBookCommentAdapter;
    private String bookname;
    private String bookid;
    private String allowMsg;
    private String showContent ;

    private ListView comment_listview;
    private RelativeLayout back_layout, common_loaddata_notice;
    private LinearLayout comment_none;
    private TextView tv_title, tv_book_introduce_name, tv_book_introduce_authorname, tv_book_introduce_share, comment_record;
    private TextView common_prompt_content,common_refresh_net;
    private SimpleTagImageView iv_book_introduce_img;
    private ImageView iv_write_comment, iv_back;
    private View book_commit_footer_view, book_comment_headview;
    private ProgressBar_Modern progressbar_modern;
    Drawable drawable_back_tv, drawable_write_comment;
    TextView tv_reply;// 点击回复的TextView对象
    private TextView tv_show_all;
    private RelativeLayout rl_show_all;
    private CircleProgressBar circleProgressBar;

    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;
    private long mLoadDelaynternalTime;
    private int PAGE_LIMIT_SIZE = 10;
    private boolean mIsPullDown = true;// 是否下拉
    private boolean allow;
    private boolean isOnPause = false;
    private  boolean mIsClickToSupportSuccess = true;//避免发生多次请求
    private boolean mIsInitData = false;

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_comment);
        openEventBus();
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        iv_back = (ImageView)findViewById(R.id.iv_back);
        tv_title = (TextView)findViewById(R.id.tv_title);
        tv_show_all = (TextView)findViewById(R.id.tv_show_all);
        rl_show_all = (RelativeLayout)findViewById(R.id.rl_show_all);
        comment_listview = (ListView)findViewById(R.id.comment_listview);
        book_comment_headview = LayoutInflater.from(this).inflate(R.layout.book_comment_headview, null); // 头布局
        book_commit_footer_view = LayoutInflater.from(this).inflate(R.layout.item_comment_foot_view, null); //脚布局
        iv_write_comment = (ImageView)findViewById(R.id.iv_write_comment);
        comment_none = (LinearLayout)findViewById(R.id.comment_none);
        progressbar_modern = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
        iv_book_introduce_img = (SimpleTagImageView)book_comment_headview.findViewById(R.id.iv_book_introduce_img);
        tv_book_introduce_name = (TextView)book_comment_headview.findViewById(R.id.tv_book_introduce_name);
        tv_book_introduce_authorname = (TextView)book_comment_headview.findViewById(R.id.tv_book_introduce_authorname);
        tv_book_introduce_share = (TextView)book_comment_headview.findViewById(R.id.tv_book_introduce_share);
        comment_record = (TextView)book_comment_headview.findViewById(R.id.comment_record);
        comment_listview.addHeaderView(book_comment_headview);
        comment_listview.addFooterView(book_commit_footer_view);
    }

    @SuppressWarnings ("rawtypes")
    @Override
    protected void initData() {
        book_commit_footer_view.setVisibility(View.GONE);
        bookname = getIntent().getStringExtra("bookName");
        bookid = getIntent().getStringExtra("bookId");
        tv_title.setText(R.string.activity_title_comment);
        mCommentDataList = new ArrayList<CommentBean>();
        mBookCommentAdapter = new CommentAdapter(mContext, mCommentDataList);
        comment_listview.setAdapter(mBookCommentAdapter);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);
        drawable_write_comment = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_write_comment), Color.parseColor("#66ccdd")));
        iv_write_comment.setImageDrawable(drawable_write_comment);
    }

    @Override
    protected void onResume() {
        if (!isOnPause || SPUtil.getBoolean("refresh_comment", false)) {
            mCurrentPage = 1;
            mIsPullDown = true;
            if (ActivityUitl.isNetworkAvailable(CommentActivity.this)) {
                getData(true);
            }else {
                common_prompt_content.setText(R.string.laikan_network_anomaly);
                showLoadFailedView();
            }

            SPUtil.putBoolean("refresh_comment", false);
        }
        MobclickAgent.onResume(this);
        super.onResume();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        isOnPause = true;
    }

    /**
     * 获取评论下载数据
     */
    private void getData(boolean flag) {
        if(flag){
            showDialog();
        }
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("showType", "time");
        map.put("page", mCurrentPage + "");
        map.put("pageSize", PAGE_LIMIT_SIZE + "");
        //		map.put("userId", SPUtil.getString("user_id", "0"));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                closeLoadMoreView(System.currentTimeMillis());
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<CommentBean>>>() {}.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                            showDataErrorView(1);
                        }else {
                            if (!mIsInitData) {
                                setData(result);
                                mIsInitData = true;
                            }
                            common_refresh_net.setOnClickListener(CommentActivity.this);
                            allow = result.getData().isAllowRecommend();
                            allowMsg = result.getData().getAllowRecommendMsg();
                            if (result.getData().getData().size() == 0) {
                                common_loaddata_notice.setVisibility(View.GONE);
                                comment_none.setVisibility(VISIBLE);
                                comment_listview.setVisibility(View.GONE);
                            }else {
                                common_loaddata_notice.setVisibility(View.GONE);
                                comment_none.setVisibility(View.GONE);
                                comment_listview.setVisibility(View.VISIBLE);
                                if (mIsPullDown) {
                                    // 下拉刷新
                                    mBookCommentAdapter.setDatas(updateListData(result.getData().getData()));
                                }else {
                                    // 上拉加载,数据追加
                                    mBookCommentAdapter.setDatas(loadMoreData(result.getData().getData()));
                                    //                                    ToastMgr.dataLoadingDone(mContext);
                                }
                            }
                            comment_record.setText(DeviceUtil.getHtmlFormatedString(CommentActivity.this, R.string.add_bracket_text, Integer.parseInt(result.getData().getTotal())));
                            mCurrentPage = mCommentDataList.size() / PAGE_LIMIT_SIZE + 1;
                            int total = Integer.parseInt(PublicUtil.isNum(result.getData().getTotal()));
                            if (mCommentDataList.size() >= total) {
                                mCurrentPage = END_LIST_PAGE;
                            }
                        }
                    }else {
                        showDataErrorView(1);
                    }
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    showDataErrorView(1);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                showDataErrorView(2);
            }

            @Override
            public void onFinish() {
                dismissDialog();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_detail + bookid + "/review?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail + bookid + "/review?", map, null, null, requestListener);
    }

    /**
     * @param type 为1  数据加载失败
     * @param type 为2  网络异常
     */
    private void showDataErrorView(int type){
        if(type == 1){
            showContent = getString(R.string.laikan_data_load_failed);
        }else if(type == 2){
            showContent = getString(R.string.laikan_network_anomaly);
        }
        if(mIsPullDown){
            common_loaddata_notice.setVisibility(View.VISIBLE);
            common_prompt_content.setText(showContent);
            closeDelayLoading(System.currentTimeMillis());
        }else{
            SnackBarNotice.customSnackbarShow(comment_listview,showContent);
        }
    }
    private void setData(BaseDataBean<BaseListDataBean<CommentBean>> result) {
        tv_book_introduce_name.setText(result.getData().getBookName());
        tv_book_introduce_authorname.setText(result.getData().getUserName());
        comment_record.setText(DeviceUtil.getHtmlFormatedString(CommentActivity.this, R.string.add_bracket_text, Integer.parseInt(result.getData().getTotal())));
        iv_book_introduce_img.setImageURI(Uri.parse(result.getData().getBookIcon()));
    }

    private ArrayList<CommentBean> updateListData(ArrayList<CommentBean> list) {
        ArrayList<CommentBean> refreshList = new ArrayList<CommentBean>();
        for (int i = 0; i < list.size(); i++) {
            if (!mCommentIdList.contains(list.get(i).getId())) {
                mCommentIdList.add(list.get(i).getId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(mCommentDataList);
        mCommentDataList.clear();
        mCommentDataList.addAll(refreshList);
        refreshList.clear();
        return mCommentDataList;
    }

    private ArrayList<CommentBean> loadMoreData(ArrayList<CommentBean> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mCommentIdList.contains(list.get(i).getId())) {
                mCommentIdList.add(list.get(i).getId());
                mCommentDataList.add(list.get(i));
//            }
        }
        return mCommentDataList;
    }

    @Override
    protected void setListener() {
        iv_write_comment.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        tv_book_introduce_share.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        mBookCommentAdapter.setItemClickListener(new CommentAdapter.ItemClickListener(){
            @Override
            public void onItemClick(View view, int position) {
            }

            @Override
            public void onReplyClick(View view, int position) {
                tv_reply = (TextView)((RelativeLayout)view).findViewById(R.id.tv_reply);
                // 跳转评论详情页面
                replyComment(position);
            }

            @Override
            public void onClickToSupport(View view, int position) {
                if (TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""))) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                }else if(!ActivityUitl.isNetworkAvailable(CommentActivity.this)) {
                    SnackBarNotice.customSnackbarShow(comment_listview, R.string.laikan_network_anomaly);
                }else {
                    if(mIsClickToSupportSuccess){
                        mIsClickToSupportSuccess = false;
                        BookDesRequester.clickToSupport(view, mCommentDataList.get(position).getId(), LaiKanEvent.EVENT_ID_BOOK_REFRESH_REPLY_NUMBER);
                    }
                }
            }
        });
        comment_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }

            @Override
            public void onScrollStateChanged(AbsListView absListView, int status) {
                if (status == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        if(!ActivityUitl.isNetworkAvailable(mContext)){
                            SnackBarNotice.customSnackbarShow(comment_listview,R.string.laikan_network_anomaly);
                        }else{
                            if(END_LIST_PAGE == mCurrentPage){
                                //                                SnackBarNotice.customSnackbarShow(comment_listview,R.string.fw_data_all_load_done);/去掉底部弹窗已显示全部 改成textview
                                book_commit_footer_view.setVisibility(VISIBLE);
                                closeLoadMoreView(System.currentTimeMillis());
                            }else{
                                book_commit_footer_view.setVisibility(View.GONE);
                                progressbar_modern.setVisibility(View.VISIBLE);
                                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                                mIsPullDown = false;
                                getData(false);
                            }
                        }
                    }
                }
            }
        });
    }

    private void replyComment(int positon){
        Intent intent = new Intent();
        intent.setClass(mContext, CommentDetailActivity.class);
        intent.putExtra("replyId", mCommentDataList.get(positon).getId().trim());
        intent.putExtra("commentjing", mCommentDataList.get(positon).isBest());
        startActivity(intent);
    }

    public void closeLoadMoreView(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    progressbar_modern.setVisibility(View.GONE);
                }
            }, 1000);
        }else {
            progressbar_modern.setVisibility(View.GONE);
        }
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    showLoadFailedView();
                }
            }, 1000);
        }else {
            showLoadFailedView();
        }
    }

    private void showLoadFailedView() {
        common_loaddata_notice.setVisibility(View.VISIBLE);
        comment_none.setVisibility(View.GONE);
        comment_listview.setVisibility(View.GONE);
        circleProgressBar.setVisibility(View.INVISIBLE);
        common_refresh_net.setOnClickListener(CommentActivity.this);
    }

    @Override
    protected void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.common_refresh_net:
                circleProgressBar.setVisibility(View.VISIBLE);
                common_refresh_net.setOnClickListener(null);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                if(ActivityUitl.isNetworkAvailable(CommentActivity.this)){
                    getData(false);
                }else {
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            case R.id.back_layout:
                finish();
                break;
            case R.id.iv_write_comment:
                if (TextUtils.isEmpty(SPUtil.getString("user_id", "")) || "0".equals(SPUtil.getString("user_id", ""))) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }else {
                    if (allow) {
                        startActivity(new Intent().setClass(mContext, SendCommentActivity.class).putExtra("bookId", bookid));
                    }else {
                        ToastMgr.showShortToast(allowMsg);
                    }
                }
                break;
            case R.id.tv_book_introduce_share:
                if (BookFileUtils.isNoLogin()) {
                    Intent intentToLogin = new Intent(mContext, LoginActivity.class);
                    startActivity(intentToLogin);
                }else {
                    ShareSdkReadBookShare.readBookShare(bookid, null, CommentActivity.this);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void parseEvent(BasicEvent event) {
        super.parseEvent(event);
        switch (event.getEventID()){
            case LaiKanEvent.EVENT_ID_BOOK_REFRESH_REPLY_NUMBER:
                try {
                    String totalReply = (String)event.getEventMap().get("totalreply");
                    String replyid = (String)event.getEventMap().get("replyId");
//                    if(TextUtils.isEmpty(totalReply))return;
                    String totalLikeCount = (String)event.getEventMap().get("totallikecount");
                    boolean isFavor = (boolean)event.getEventMap().get("isFavor");
                    for (int i = 0; i < mCommentDataList.size(); i++) {
                        if (!TextUtils.isEmpty(totalReply) && mCommentDataList.get(i).getId().equals(replyid)) {
                            mCommentDataList.get(i).setReplyCount(totalReply);
                        }
                        if (!TextUtils.isEmpty(totalLikeCount) && mCommentDataList.get(i).getId().equals(replyid)) {
                            mCommentDataList.get(i).setLikeCount(totalLikeCount);
                            mCommentDataList.get(i).setFavor(isFavor);
                        }
                    }
                    mBookCommentAdapter.setDatas(mCommentDataList);
                    mIsClickToSupportSuccess = true;
                }catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
